import Util from '../../../utils/utils.js';
import User from '../../../utils/user.js';
import { GoodsHttp } from '../../../api/goods.js'

const goodsModel = new GoodsHttp()

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    show: {
      type: Boolean,
      value: false
    },
    shareInfo: Object,
    goodsId: Number
  },

  /**
   * 组件的初始数据
   */
  data: {
    currentSelectImgIndex: 0, // 当前选择的商品图片
    shareImage: {}
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 关闭弹窗
    onClose () {
      this.triggerEvent('close')
    },
    // 选择图片
    onSelectShareImage: function (event) {
      let index = event.currentTarget.dataset.index;
      this.setData({
        currentSelectImgIndex: index
      });
    },
    // 复制自营商品文本
    copySelfGoodsText () {
      const { GoodsName, MinNormalPrice, PostPrice, ShortUrl } = this.data.shareInfo
      let copyText = 
      `${GoodsName}\n` +
      `-------------------------------\n` +
      `原价：¥ ${MinNormalPrice}\n` +
      `会员价：¥ ${PostPrice}\n` +
      `-------------------------------\n` +
      `优惠链接：${ShortUrl}`
      wx.setClipboardData({
        data: copyText
      });
    },
    onShare (event) {
      const { type } = event.currentTarget.dataset
      if (type === 'miniImg' || type === 'h5Img') {
        this.copySelfGoodsText()
        this.httpCompoundShareGoodsImg(type)
      } else {
        this.copySelfGoodsText()
      }
    },
    // 获取合成图片并预览
    httpCompoundShareGoodsImg (type) {
      const { goodsId, shareInfo, currentSelectImgIndex } = this.data
      let channel = User.getShareParam(0);
      let param = {
        url_type: 1,
        goods_url: shareInfo.GoodsImageURL[currentSelectImgIndex],
        goods_id: goodsId,
        aid: 0
      };
      if (channel.shareUid > 0) {
        param['ownerUserId'] = channel.shareUid;
      }
      Util.loading()
      return goodsModel.compoundShareGoodsImg(param).then((res) => {
        Util.closeLoading()
        let url = []
        if (type === 'miniImg') {
          url.push(res.wx_url)
        } else if (type === 'h5Img') {
          url.push(res.h5_url)
        }
        wx.previewImage({
          urls: url
        });
      }).catch((err) => {
        console.log(`err`, err)
      })
    }
  }
})